require(['jquery', 'lib/purl', 'video', 'chip8'],
function($, purl, Video, Chip8) {
	var getArgs = function() {
		var args, params;
		var isInteger = /^[0-9]+$/;

		// Create argument list with default values
		args = {
			rom: null,
			freq: 840,
			scale: 8,
			x: 0,
			y: 0
		};

		// Parse URL
		for (prop in $.url().param()) {
			if ((prop != '') && !args.hasOwnProperty(prop)) {
				alert('Unknown argument \'' + prop + '\'!');
				return null;
			}
			args[prop] = $.url().param(prop);
		}

		// ROM argument is mandatory
		if (args.rom === null) {
			alert('ROM argument is not present!');
			return null;
		}

		// Verify all other arguments are integers
		for (prop in args)
			if ((prop != 'rom') && !isInteger.test(args[prop])) {
				alert('Argument \'' + prop + '\' is not a valid integer (' +
					args[prop] + ')!');
				return null;
			}

		return args;
	}

	var printUsage = function() {
		// Title
		document.writeln('<b>chippie - an HTML5/JavaScript Chip-8 emulator \
			written by S&eacutebastien Ronsse</b><BR>');
		document.writeln('<BR>');

		// Usage and ROM list
		document.writeln('<b>Usage</b>:<BR>');
		document.write($.url().attr('path') + '?rom=<i>rom</i><BR>');
		document.writeln('<BR>');

		// Optional parameters
		document.writeln('<b>Optional parameters</b>:<BR>');
		document.writeln('<i>freq</i>: sets the machine frequency in Hz \
			defaults to 840).<BR>');
		document.writeln('<i>scale</i>: scales the destination canvas \
			(defaults to 1).<BR>');
		document.writeln('<i>x</i>: sets the X position (defaults to 0).<BR>');
		document.writeln('<i>y</i>: sets the Y position (defaults to 0).<BR>');
		document.writeln('<BR>');

		// Example
		document.write('<b>Example</b>:<BR>');
		document.write($.url().attr('path') +
			'?rom=MAZE&freq=600&scale=4&x=20&y=10');
	}

	var main = function() {
		var args, chip8;

		// Get arguments and check usage
		args = getArgs();
		if (args === null) {
			printUsage();
			return;
		}

		// Initialize video backend
		new Video(args.scale, args.x, args.y);

		// Initialize our machine and load ROM
		chip8 = new Chip8(args.freq);
		if (!chip8.load(args.rom)) {
			printUsage();
			return;
		}

		// Everything is initialized, so run the machine
		chip8.run();
	}

	$(document).ready(main);
});